package main

import (
	_ "embed"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"log"
	"os"
	"screenRobot/network/http"
	"screenRobot/network/tcp"
	"screenRobot/network/udp"
	"screenRobot/server/core"
)

//go:embed logo.png
var logoIco []byte

func main() {
	serverApp := app.New()
	//解决中文乱码
	serverApp.Settings().SetTheme(&myTheme{})
	LogoResource := fyne.NewStaticResource("logo", logoIco)
	serverApp.SetIcon(LogoResource)
	master := serverApp.NewWindow("四点五robot 服务端")

	scanBtn := widget.NewCheck("开启扫描", func(b bool) {
		if b {
			log.Println("开启用户扫描")
			udp.ListenEnabled = true
			udp.ScanClient()
			return
		}
		udp.ListenEnabled = false
		log.Println("关闭扫描")
	})
	serverBtn := widget.NewCheck("开启服务", func(b bool) {
		if b {
			log.Println("开启控制服务")
			tcp.ListenEnable = true
			tcp.CreateServer()
			return
		}
		log.Println("关闭服务")
		tcp.ListenEnable = false
	})

	ftpAddr := binding.NewString()
	dir, _ := os.Getwd()
	ftpAddr.Set(dir)
	restartServerBtn := widget.NewButton("刷新服务", func() {
		log.Println("重启了ftp服务")
		path, _ := ftpAddr.Get()
		go http.RestartFileServer(path)
		dialog.ShowInformation("重启服务成功", fmt.Sprintf("重启服务成功：[%s]", path), master)
	})

	connectionCountString := binding.NewString()
	connectionCountString.Set(fmt.Sprintf("当前连接客户端：%d", 0))
	go func() {
		for {
			count := <-tcp.ClientLen
			connectionCountString.Set(fmt.Sprintf("当前连接客户端：%d", count))
		}
	}()

	master.SetContent(
		container.NewVBox(
			widget.NewForm(
				widget.NewFormItem("http服务：",
					container.NewBorder(
						nil, nil, nil,
						restartServerBtn,
						widget.NewEntryWithData(ftpAddr),
					),
				),
				widget.NewFormItem("服务：",
					container.NewVBox(
						container.NewHBox(
							scanBtn,
							serverBtn,
						),
						widget.NewLabelWithData(connectionCountString),
					)),
			),
			container.NewHBox(widget.NewLabel(`
功能介绍：
	1. 软件功能搭配客户端一起使用，要保证都在同一局域网内；且机型以及分辨率一致！
	2. 开启扫描前需要先开启服务，因为客户端一旦扫描到服务端就会发起连接；所以要保证服务先开启

by：dpengchen@163.com
`)),
		))
	master.SetFixedSize(true)

	//开启监控鼠标键盘
	core.Listener()
	//开启http静态文件服务
	path, _ := ftpAddr.Get()
	go http.StartFileServer(path)

	master.ShowAndRun()
}
